package com.furnitur.modules.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.favorite.Favorite;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.favorite.FavoriteMapper;
import com.furnitur.modules.portal.service.PortalFavoriteService;
import com.furnitur.modules.portal.vo.favorite.FavoriteVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PortalFavoriteServiceImpl implements PortalFavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    @Transactional
    public void addFavorite(Long furnitureId) {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 检查是否已收藏
        if (isFavorite(furnitureId)) {
            throw new RuntimeException("已经收藏过该商品");
        }

        // 添加收藏
        Favorite favorite = new Favorite();
        favorite.setUserId(currentUser.getId());
        favorite.setFurnitureId(furnitureId);
        favoriteMapper.insert(favorite);
    }

    @Override
    @Transactional
    public void removeFavorite(Long furnitureId) {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        favoriteMapper.delete(new QueryWrapper<Favorite>()
                .eq("user_id", currentUser.getId())
                .eq("furniture_id", furnitureId));
    }

    @Override
    public List<FavoriteVO> getFavoriteList() {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }
        return favoriteMapper.selectUserFavorites(currentUser.getId());
    }

    @Override
    public boolean isFavorite(Long furnitureId) {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            return false;
        }
        return favoriteMapper.selectCount(new QueryWrapper<Favorite>()
                .eq("user_id", currentUser.getId())
                .eq("furniture_id", furnitureId)) > 0;
    }
} 